<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/11/6
 * Time: 13:15
 */

namespace zhtfrontend\modules\sitepadapi\controllers;

use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Course;
use zhtfrontend\models\datas\Student;
use zhtfrontend\modules\sitepadapi\components\rest\ActiveController;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
use yii\web\Response;


class ClassmanageController extends ActiveController
{
    public $modelClass = 'zhtfrontend\models\datas\ClassManage';

    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['update'], $actions['create'], $actions['view'], $actions['delete']);
        return $actions;
    }

    public function actionFindbytid($teacher_id)
    {
        $modelClass = $this->modelClass;
        $query = $modelClass::find()->where(['headmaster' => $teacher_id]);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }

    public function actionFindbytc($teacher_id, $class_name)
    {
        $course_data = Course::find()->where(['name' => $class_name])->one();
        $data = ClassManage::find()->where(['headmaster' => $teacher_id, 'code' => $course_data->arrangeCourse->id]);
        return new ActiveDataProvider([
            'query' => $data
        ]);
    }

    public function actionFindbycid($class_id)
    {
        $class_student = ClassStudent::find()->select('student_id')->where(['class_manage_id' => $class_id])->column();
        $query = Student::find()->where(['in', 'id', $class_student]);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }

    public function actionView($id)
    {
        return $this->findModel($id);
    }

    protected function findModel($id)
    {
        $modelClass = $this->modelClass;
        $model = $modelClass::findOne($id);
        if ($model != null) {
            return $model;
        } else {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
    }


}